# -*- coding: utf-8 -*-
"""
菜单管理API
"""

from typing import List
from fastapi import APIRouter, Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.database import get_db
from app.core.deps import get_current_user, get_tenant_id
from app.models.user import User
from app.schemas.menu import MenuCreate, MenuUpdate, MenuResponse, MenuTreeResponse, MenuQuery
from app.services.menu import menu_service
from app.utils.response import ResponseUtil

router = APIRouter()


@router.post("/", summary="创建菜单")
async def create_menu(
    menu_data: MenuCreate,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id)
):
    """创建菜单"""
    menu = await menu_service.create(db, menu_data, tenant_id, current_user.id)
    return ResponseUtil.success(data=MenuResponse.model_validate(menu))


@router.get("/", summary="获取菜单列表")
async def get_menu_list(
    name: str = Query(None, description="菜单名称"),
    title: str = Query(None, description="菜单标题"),
    type: str = Query(None, description="菜单类型"),
    status: bool = Query(None, description="菜单状态"),
    visible: bool = Query(None, description="是否显示"),
    skip: int = Query(0, description="跳过记录数"),
    limit: int = Query(100, description="限制记录数"),
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id)
):
    """获取菜单列表"""
    query = MenuQuery(
        name=name,
        title=title,
        type=type,
        status=status,
        visible=visible
    )

    menus = await menu_service.get_list(db, query, tenant_id, skip, limit)
    total = await menu_service.count(db, query, tenant_id)

    return ResponseUtil.success(
        data={
            "items": [MenuResponse.model_validate(menu) for menu in menus],
            "total": total,
            "skip": skip,
            "limit": limit
        }
    )


@router.get("/tree", summary="获取菜单树")
async def get_menu_tree(
    parent_id: int = Query(0, description="父菜单ID"),
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id)
):
    """获取菜单树"""
    tree = await menu_service.get_tree(db, tenant_id, parent_id)
    return ResponseUtil.success(data=tree)


@router.get("/{menu_id}", summary="获取菜单详情")
async def get_menu(
    menu_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id)
):
    """获取菜单详情"""
    menu = await menu_service.get_by_id(db, menu_id, tenant_id)
    if not menu:
        return ResponseUtil.error(message="菜单不存在")

    return ResponseUtil.success(data=MenuResponse.model_validate(menu))


@router.put("/{menu_id}", summary="更新菜单")
async def update_menu(
    menu_id: int,
    menu_data: MenuUpdate,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id)
):
    """更新菜单"""
    menu = await menu_service.update(db, menu_id, menu_data, tenant_id, current_user.id)
    return ResponseUtil.success(data=MenuResponse.model_validate(menu))


@router.delete("/{menu_id}", summary="删除菜单")
async def delete_menu(
    menu_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id)
):
    """删除菜单"""
    await menu_service.delete(db, menu_id, tenant_id)
    return ResponseUtil.success(message="删除成功")


@router.put("/{menu_id}/sort", summary="更新菜单排序")
async def update_menu_sort(
    menu_id: int,
    sort: int,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id)
):
    """更新菜单排序"""
    await menu_service.update_sort(db, menu_id, sort, tenant_id)
    return ResponseUtil.success(message="排序更新成功")


@router.put("/{menu_id}/status", summary="修改菜单状态")
async def change_menu_status(
    menu_id: int,
    status: bool,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id)
):
    """修改菜单状态"""
    await menu_service.change_status(db, menu_id, status, tenant_id)
    return ResponseUtil.success(message="状态修改成功")


@router.put("/{menu_id}/permission/{permission_id}", summary="绑定菜单权限")
async def bind_menu_permission(
    menu_id: int,
    permission_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id)
):
    """绑定菜单权限"""
    await menu_service.bind_permission(db, menu_id, permission_id, tenant_id)
    return ResponseUtil.success(message="权限绑定成功")


@router.delete("/{menu_id}/permission", summary="解绑菜单权限")
async def unbind_menu_permission(
    menu_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id)
):
    """解绑菜单权限"""
    await menu_service.unbind_permission(db, menu_id, tenant_id)
    return ResponseUtil.success(message="权限解绑成功")


@router.get("/permissions", summary="获取菜单权限绑定信息")
async def get_menu_permissions(
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id)
):
    """获取所有菜单及其权限绑定信息"""
    menu_permissions = await menu_service.get_menu_permissions(db, tenant_id)
    return ResponseUtil.success(data=menu_permissions)